# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import datetime
from web_lib.page import Page
from web_lib.webutils import Response, expose , json , salvaInSessione, leggiInSessione , permalinkaTitle
from dao.Role import Role
from dao.Action import Action
from dao.RoleAction import RoleAction as RuoliAzioni
import Environment
from lib.utils import prep2json
from webEnv import *


@expose('/pg/cu_RuoliAzioni/<action>')
@expose('/pg/cu_RuoliAzioni/')
def customRuoliAzioni(req, action=None):
    """

    """
    def __show__(req, action=None):
        ruoli = Role().select(batchSize=None)
        rolaz = RuoliAzioni().select(
                            batchSize=None,
                            )
        azioni = Action().select(batchSize=None)
        pageData = {'file' : "/pg/cu_RuoliAzioni",
                    "rolaz":rolaz,
                    "ruoli":ruoli,
                    "azioni":azioni,
            }
        return Page(req).render(pageData)

    def __edit__(req, action=None):
        id = req.form.get("id")
        if id:
            d = FamigliaArticolo().getRecord(id=id)
            action = "edit"
        else:
            d = FamigliaArticolo()
            action = "new"
        ok = Environment.params['session'].query(FamigliaArticolo).filter(and_(FamigliaArticolo.id_padre==None)).all()
        fams = FamigliaArticolo().select(
                            batchSize=None,
                            #orderBy="id_padre",
                            )
        pageData = {'file': "pg/addedit/ae_famigliaArticolo",
                    "dao": d,
                    "action":action,
                    "fams":fams,
                    "ok":ok}
        return Page(req).render(pageData)


    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate"""
        print "VEDIAMO", req.form.to_dict()
        idRole = req.form.get("id_role")
        idRoleAction = req.form.getlist("id_roleaction")
        if idRole != "None":
            tai = RuoliAzioni().select(id_role=int(idRole), batchSize = None)
        if tai:
            for t in tai:
                t.delete()
        for a in idRoleAction:
            d = RuoliAzioni()
            d.id_role = int(idRole)
            d.id_action = int(a)
            d.persist()

        print "IDDDDROLE", idRole,idRoleAction
        #d.codice = str(req.form.get("codice"))
        #d.denominazione = str(req.form.get("denominazione"))
        #d.denominazione_breve = str(req.form.get("denominazione_breve"))
        #d.id_padre = str(req.form.get("id_padre"))
        #d.persist()
        url_red = "/pg/cu_RuoliAzioni/"
        return Page(req).redirect(url_red)

    def __delete__(req, action=None):
        """Cancella una riga"""
        id = int(req.form.get("id"))
        d = RuoliAzioni().getRecord(id=id)
        d.delete()
        url_red = "/pg/cu_Ruoliazioni/"
        return Page(req).redirect(url_red)

    def __get_ruoli_azioni__(req, action=None):
        idRole= req.args.get("id_role")
        try:
            tai = RuoliAzioni().select(id_role=int(idRole), batchSize = None)
        except:
            tai = []
        item = [str(d.id_action) for d in tai]
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)


    if action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    elif action == "GetRoleAction":
        return __get_ruoli_azioni__(req, action=action)
    else:
        return __show__(req, action=action)
